import React, { useEffect, useState } from "react";
import style from "./index.module.scss";
import { Dropdown, Menu, Avatar } from "antd";
import { useRouter } from "next/router";
import { clearAuth, getUser } from "@/utils/catch";
const UserInfo: React.FC = () => {
  const Router = useRouter();
  const logout = () => {
    clearAuth();
    Router.replace("/login");
  };
  const [user, setUser] = useState<IUser | null>(null);

  // 渲染时得到本地的用户信息
  useEffect(() => {
    const user = getUser();
    setUser(user);
    if (!user) {
      Router.replace("/login");
    }
  }, []);

  const menu = () => {
    return (
      <Menu>
        <Menu.Item onClick={() => Router.push("/ownspace")}>个人中心</Menu.Item>
        <Menu.Item onClick={logout}>退出登录</Menu.Item>
      </Menu>
    );
  };
  return (
    <Dropdown overlay={menu}>
      <div className={style.userinfo}>
        <Avatar size="small" src={user?.avatar} icon={user?.avatar ? '' : 'user'} />
        <span className={style.username}>{user?.name}</span>
      </div>
    </Dropdown>
  );
};

export default UserInfo;
